package cn.wolfcode.wolf2w.redis.service.impl;

import cn.wolfcode.wolf2w.redis.service.IUserViewRedisService;
import cn.wolfcode.wolf2w.service.IUserViewService;
import cn.wolfcode.wolf2w.vo.UserViewVo;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

@Service
public class UserViewRedisServiceImpl implements IUserViewRedisService {
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public UserViewVo insert(String ownerId, String uid) {

        String value = redisTemplate.opsForValue().get(uid);
        if (!StringUtils.hasLength(value)) {
            UserViewVo userViewVo = new UserViewVo();
            userViewVo.setTodayView(0);
            userViewVo.setTotalView(0);
            redisTemplate.opsForValue().set(uid, JSON.toJSONString(userViewVo));
        }

        if (!ownerId.equals(uid)) {
            UserViewVo userViewVo = JSON.parseObject(redisTemplate.opsForValue().get(uid), UserViewVo.class);
            userViewVo.setTodayView(userViewVo.getTodayView() + 1);
            userViewVo.setTotalView(userViewVo.getTotalView() + 1);
            redisTemplate.opsForValue().set(uid, JSON.toJSONString(userViewVo));
            return userViewVo;


        }else{
            String s = redisTemplate.opsForValue().get(uid);
            return JSON.parseObject(s,UserViewVo.class);
        }
    }
}
